package com.wanghua.mall.order.listener;

import com.alipay.easysdk.factory.Factory;
import com.wanghua.mall.order.constant.AlipayConstant;
import com.wanghua.mall.order.service.OrderService;
import com.wanghua.mall.order.vo.PayAsyncVo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝支付的异步通知，需要配置内网穿透，暂不做
 * https://opendocs.alipay.com/open/270/105902
 *
 * @author wanghua
 * @create 2021-09-11 10:09
 */
@RestController
public class OrderPayedListener {

    @Resource
    private OrderService orderService;

    /**
     * 支付宝支付的异步通知
     *
     * @param request HttpServletRequest
     * @return String
     */
    @PostMapping("/payed/notify")
    public String handleAlipay(PayAsyncVo payAsyncVo, HttpServletRequest request) throws Exception {
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String key : parameterMap.keySet()) {
            System.out.println(key + "====>" + request.getParameter(key));
        }
        System.out.println(payAsyncVo);
        //1.验签 https://opendocs.alipay.com/open/54/00y8k9
        Map<String, String> parameters = new HashMap<>();
        for (String key : parameterMap.keySet()) {
            String value = request.getParameter(key);
            //... ... 接收到的所有参数放入一个Map中
            parameters.put(key, value);
        }
        Boolean verifyNotify = Factory.Payment.Common().verifyNotify(parameters);
        if (verifyNotify) {
            //2.修改订单状态
            String result = orderService.handlePayResult(payAsyncVo);
            return result;
        }
        return "fail";

    }
}
